#ifndef SCREENRECORDER_H
#define SCREENRECORDER_H

#include <QObject>
#include <QProcess>
#include <QSize>
#include <QString>
#include <QDateTime>
#include <QDir>
#include <QTimer>

class ScreenRecorder : public QObject
{
    Q_OBJECT

public:
    // 录制模式枚举
    enum RecordingMode {
        StreamOnly,      // 仅推流
        FileOnly,        // 仅录制文件
        StreamAndFile    // 推流+录制文件
    };

    explicit ScreenRecorder(QObject *parent = nullptr);
    ~ScreenRecorder();

    // 核心功能
    bool initialize();
    void setResolution(const QSize& resolution);
    void setFrameRate(int frameRate);
    void setBitrate(int bitrate);
    void setRecordingMode(RecordingMode mode);
    void setOutputDirectory(const QString& directory);

    // 录制控制
    bool startRecording();
    void stopRecording();
    bool isRecording() const;
    
    // 录制状态
    QString getCurrentRecordingFile() const;
    qint64 getRecordingDuration() const;
    qint64 getFileSize() const;
    QString getRecordingStatus() const;

    // 录制管理
    void pauseRecording();
    void resumeRecording();
    bool isPaused() const;

signals:
    void recordingStarted();
    void recordingStopped();
    void recordingPaused();
    void recordingResumed();
    void errorOccurred(const QString& error);
    void statusChanged(const QString& status);
    void fileSizeChanged(qint64 size);
    void durationChanged(qint64 duration);

private slots:
    void onFFmpegFinished(int exitCode, QProcess::ExitStatus exitStatus);
    void onFFmpegError(QProcess::ProcessError error);
    void onFFmpegErrorOutput();
    void updateRecordingStatus();

private:
    void setupFFmpegProcess();
    void setupStatusTimer();
    void buildFFmpegArguments();
    void buildFileRecordingArguments();
    void buildStreamRecordingArguments();
    void generateSDPFile();
    QString getLocalNetworkIP();
    QString generateFileName() const;
    void createOutputDirectory();
    void startStatusTimer();
    void stopStatusTimer();

private:
    QProcess* ffmpegProcess;
    QTimer* statusTimer;
    
    // 配置参数
    QSize resolution;
    int frameRate;
    int bitrate;
    RecordingMode recordingMode;
    QString outputDirectory;
    
    // 状态
    bool isRecordingFlag;
    bool isPausedFlag;
    QDateTime recordingStartTime;
    QString currentRecordingFile;
    qint64 currentFileSize;
    qint64 pausedDuration;  // 暂停时的累计时长
    
    // FFmpeg参数
    QStringList ffmpegArguments;
    QStringList fileArguments;
    QStringList streamArguments;
};

#endif // SCREENRECORDER_H
